package org.jeecgframework.jwt.web;

import com.ljt.openapi.demo.util.HttpUtil;
import com.zhaodui.conf.entity.WxConfigEntity;
import com.zhaodui.sys.entity.FxjOtherLoginEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.PasswordUtil;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.jwt.service.TokenManager;
import org.jeecgframework.jwt.util.ResponseMessage;
import org.jeecgframework.jwt.util.Result;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.system.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 获取和删除token的请求地址， 
 * 在Restful设计中其实就对应着登录和退出登录的资源映射
 * 
 * @author scott
 * @date 2015/7/30.
 */
@Api(value = "token", description = "鉴权token接口", tags = "tokenAPI")
@Controller
@RequestMapping("/tokens")
public class TokenController {
	private static final Logger logger = LoggerFactory.getLogger(TokenController.class);
	@Autowired
	private UserService userService;
	@Autowired
	private TokenManager tokenManager;
	@Autowired
	private SystemService systemService;

	@ApiOperation(value = "获取TOKEN")
	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<?> login(@RequestParam(value="username", required=true)  String username, @RequestParam(value="password", required=true) String password, @RequestParam(value="appCode", required=false) String appCode) {
		logger.info("获取TOKEN[{}]" , username);
		// 验证
		if (StringUtils.isEmpty(username)) {
			return new ResponseEntity("用户账号不能为空!", HttpStatus.NOT_FOUND);
		}
		// 验证
		if (StringUtils.isEmpty(username)) {
			return new ResponseEntity("用户密码不能为空!", HttpStatus.NOT_FOUND);
		}
		Assert.notNull(username, "username can not be empty");
		Assert.notNull(password, "password can not be empty");

		TSUser user = userService.checkUserExits(username, password);
		if (user == null) {
			// 提示用户名或密码错误
			logger.info("获取TOKEN,户账号密码错误[{}]" , username);
			return new ResponseEntity("用户账号密码错误!", HttpStatus.NOT_FOUND);
		}
		// 生成一个token，保存用户登录状态
		String token = tokenManager.createToken(user);
		return new ResponseEntity(token, HttpStatus.OK);
	}
//	username: userName,
//	oldPwd: oldPassword,
//	newPwd: newPassword
	@ApiOperation(value = "changepass")
	@RequestMapping(value = "/changepass",method = RequestMethod.POST)
	@ResponseBody
	public ResponseMessage<?> changepass(@RequestParam(value="username", required=true)  String username, @RequestParam(value="oldPwd", required=true) String oldPwd, @RequestParam(value="newPwd", required=true) String newPwd) {
		logger.info("获取TOKEN[{}]" , username);
		// 验证


		TSUser user = userService.checkUserExits(username, oldPwd);
		if (user == null) {
			// 提示用户名或密码错误
			return  org.jeecgframework.jwt.util.Result.error("原密码错误!");
		}else {
			String newpassword = oConvertUtils.getString(newPwd);
			try {
				user.setPassword(PasswordUtil.encrypt(user.getUserName(), newpassword, PasswordUtil.getStaticSalt()));
				userService.updateEntitie(user);

			} catch (Exception e) {
			}
		}
		// 生成一个token，保存用户登录状态
		return Result.success("修改成功");
		}

	@ApiOperation(value = "wxauth")
	@RequestMapping(value = "/auth",method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<?> auth(@RequestParam(value="JSCODE", required=false)  String JSCODE) {
		logger.info("获取TOKEN[{}]" , JSCODE);
		// 验证
		if (StringUtils.isEmpty(JSCODE)) {
			return new ResponseEntity("JSCODE不能为空!", HttpStatus.NOT_FOUND);
		}
//		// 验证
//		if (StringUtils.isEmpty(username)) {
//			return new ResponseEntity("用户密码不能为空!", HttpStatus.NOT_FOUND);
//		}
		Assert.notNull(JSCODE, "JSCODE can not be empty");
//		Assert.notNull(password, "password can not be empty");
		 String miniappid=ResourceUtil.getConfigByName("mini.appid") ;
		  String minisecret=ResourceUtil.getConfigByName("mini.secret");
		String url="https://api.weixin.qq.com/sns/jscode2session?appid=" + miniappid +
				"&secret=" + minisecret +
				"&js_code=" +
				JSCODE+"&grant_type=authorization_code";
		String result= com.xiaoleilu.hutool.http.HttpUtil.get(url);
		return new ResponseEntity(result, HttpStatus.OK);
	}
	@ApiOperation(value = "wxauthv2")
	@RequestMapping(value = "/authv2",method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage<?> authV2(@RequestParam(value="JSCODE", required=false)  String JSCODE) {
		logger.info("获取TOKEN[{}]" , JSCODE);
		// 验证
		if (StringUtils.isEmpty(JSCODE)) {
			return Result.error("JSCODE不能为空!");
		}
		WxConfigEntity wxConfigEntity = systemService.findUniqueByProperty(WxConfigEntity.class,"appCode","fxjui");

//		// 验证
//		if (StringUtils.isEmpty(username)) {
//			return new ResponseEntity("用户密码不能为空!", HttpStatus.NOT_FOUND);
//		}
		Assert.notNull(JSCODE, "JSCODE can not be empty");
//		Assert.notNull(password, "password can not be empty");
		String miniappid=ResourceUtil.getConfigByName("mini.appid") ;
		String minisecret=ResourceUtil.getConfigByName("mini.secret");
		String url="https://api.weixin.qq.com/sns/jscode2session?appid=" + wxConfigEntity.getAppId() +
				"&secret=" + wxConfigEntity.getAppSecret() +
				"&js_code=" +
				JSCODE+"&grant_type=authorization_code";
		String result= com.xiaoleilu.hutool.http.HttpUtil.get(url);
		logger.info("JSCODE=="+JSCODE);
		logger.info("url=="+url );
		logger.info("authv2=="+ result);

		JSONObject resultJson = JSONObject.fromObject(result);
		String openid = String.valueOf(resultJson.get("openid"));
		try{

			FxjOtherLoginEntity fxjOtherLoginEntity = userService.findUniqueByProperty(FxjOtherLoginEntity.class,"otherid",openid);
			if(fxjOtherLoginEntity!=null){
				return Result.success(openid,(long)1);
			}else{
				return Result.success(openid,(long)0);
			}
		}catch (Exception e){
			return Result.success(openid,(long)0);

		}

	}
	@ApiOperation(value = "wxauthv3")
	@RequestMapping(value = "/authv3",method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage<?> authV3(@RequestParam(value="JSCODE", required=false)  String JSCODE, @RequestParam(value="appCode", required=false) String appCode) {
		logger.info("获取TOKEN[{}]" , JSCODE);
		// 验证
		if (StringUtils.isEmpty(JSCODE)) {
			return Result.error("JSCODE不能为空!");
		}
		WxConfigEntity wxConfigEntity = systemService.findUniqueByProperty(WxConfigEntity.class,"appCode",appCode);

//		// 验证
//		if (StringUtils.isEmpty(username)) {
//			return new ResponseEntity("用户密码不能为空!", HttpStatus.NOT_FOUND);
//		}
		Assert.notNull(JSCODE, "JSCODE can not be empty");
//		Assert.notNull(password, "password can not be empty");
//		String miniappid=ResourceUtil.getConfigByName("mini.appid") ;
//		String minisecret=ResourceUtil.getConfigByName("mini.secret");
		String url="https://api.weixin.qq.com/sns/jscode2session?appid=" + wxConfigEntity.getAppId() +
				"&secret=" + wxConfigEntity.getAppSecret() +
				"&js_code=" +
				JSCODE+"&grant_type=authorization_code";
		String result= com.xiaoleilu.hutool.http.HttpUtil.get(url);
		logger.info("JSCODE=="+JSCODE);
		logger.info("url=="+url );
		logger.info("authv2=="+ result);

		JSONObject resultJson = JSONObject.fromObject(result);
		String openid = String.valueOf(resultJson.get("openid"));
		try{

			FxjOtherLoginEntity fxjOtherLoginEntity = userService.findUniqueByProperty(FxjOtherLoginEntity.class,"otherid",openid);
			if(fxjOtherLoginEntity!=null){
				return Result.success(openid,(long)1);
			}else{
				return Result.success(openid,(long)0);
			}
		}catch (Exception e){
			return Result.success(openid,(long)0);

		}

	}
	@ApiOperation(value = "wxmsgauth")
	@RequestMapping(value = "/wxmsgauth",method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<?> wxmsgauth(@RequestParam(value="signature", required=false)  String signature,
									   @RequestParam(value="timestamp", required=false)  String timestamp,
									   @RequestParam(value="nonce", required=false)  String nonce,
									   @RequestParam(value="echostr", required=false)  String echostr) {
		logger.info("获取TOKEN[{}]" , echostr);
		// 验证
		if (StringUtils.isEmpty(echostr)) {
			return new ResponseEntity("JSCODE不能为空!", HttpStatus.NOT_FOUND);
		}
//		// 验证
//		if (StringUtils.isEmpty(username)) {
//			return new ResponseEntity("用户密码不能为空!", HttpStatus.NOT_FOUND);
//		}
		Assert.notNull(echostr, "JSCODE can not be empty");
//		Assert.notNull(password, "password can not be empty");
//		String miniappid=ResourceUtil.getConfigByName("mini.appid") ;
//		String minisecret=ResourceUtil.getConfigByName("mini.secret");
//		String url="https://api.weixin.qq.com/sns/jscode2session?appid=" + miniappid +
//				"&secret=" + minisecret +
//				"&js_code=" +
//				JSCODE+"&grant_type=authorization_code";
//		String result= com.xiaoleilu.hutool.http.HttpUtil.get(url);
		return new ResponseEntity(echostr, HttpStatus.OK);
	}
	@ApiOperation(value = "三方获取TOKEN")
	@RequestMapping(value = "/otherlogin",method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<?> otherlogin(@RequestParam(value="openid", required=false)  String openid, @RequestParam(value="unionid", required=false)  String unionid,    @RequestParam(value="appCode", required=false) String appCode) {
		logger.info("获取TOKEN[{}]" , openid);
		// 验证
		if (StringUtils.isEmpty(openid)) {
			return new ResponseEntity("用户账号不能为空!", HttpStatus.NOT_FOUND);
		}
//		// 验证
//		if (StringUtils.isEmpty(username)) {
//			return new ResponseEntity("用户密码不能为空!", HttpStatus.NOT_FOUND);
//		}
		Assert.notNull(openid, "username can not be empty");
//		Assert.notNull(password, "password can not be empty");
		FxjOtherLoginEntity fxjOtherLoginEntity = userService.findUniqueByProperty(FxjOtherLoginEntity.class,"otherid",openid);
		String token = "";
		if (fxjOtherLoginEntity == null) {
			// 提示用户名或密码错误
			logger.info("获取TOKEN,户账号密码错误[{}]" , openid);
			return new ResponseEntity("用户账号密码错误!", HttpStatus.NOT_FOUND);
		}else{
			TSUser user = userService.findUniqueByProperty(TSUser.class,"userName",fxjOtherLoginEntity.getUsername());
			if(user!=null){
				token = tokenManager.createToken(user);
				fxjOtherLoginEntity.setOtherre1(token);
			}else{
				logger.info("获取TOKEN,户账号密码错误[{}]" , openid);
				return new ResponseEntity("用户账号密码错误!", HttpStatus.NOT_FOUND);
			}

		}
		// 生成一个token，保存用户登录状态
		return new ResponseEntity(fxjOtherLoginEntity, HttpStatus.OK);
	}
	@ApiOperation(value = "三方openid保存")
	@RequestMapping(value = "/otherloginsave",method = RequestMethod.POST)
	@ResponseBody
	public ResponseMessage<?> otherloginsave(@RequestParam(value="openid", required=false)  String openid, @RequestParam(value="unionid", required=false)  String unionid, @RequestParam(value="username", required=true)  String username, @RequestParam(value="password", required=true) String password,  @RequestParam(value="appCode", required=false) String appCode) {
		logger.info("获取TOKEN[{}]" , openid);
		// 验证
		if (StringUtils.isEmpty(openid)) {
			return  org.jeecgframework.jwt.util.Result.error("用户账号不能为空!");
		}
		TSUser user = userService.checkUserExits(username, password);

		if (user == null) {
			// 提示用户名或密码错误
			logger.info("获取TOKEN,户账号密码错误[{}]" , username);
			return  Result.error("用户账号密码错误!" );
		}
		FxjOtherLoginEntity fxjOtherLoginEntity = userService.findUniqueByProperty(FxjOtherLoginEntity.class,"otherid",openid);

		if (fxjOtherLoginEntity!=null){
			fxjOtherLoginEntity.setUsername(username);
			fxjOtherLoginEntity.setOtherid(openid);
			userService.updateEntitie(fxjOtherLoginEntity);
		}else{
			fxjOtherLoginEntity = new FxjOtherLoginEntity();
			fxjOtherLoginEntity.setUsername(username);
			fxjOtherLoginEntity.setOtherid(openid);
			userService.save(fxjOtherLoginEntity);
		}
		return Result.success(fxjOtherLoginEntity);
	}


	@ApiOperation(value = "销毁TOKEN")
	@RequestMapping(value = "/{username}", method = RequestMethod.DELETE)
	@ResponseBody
	public ResponseMessage<?> logout(@ApiParam(name = "username", value = "用户账号", required = true) @PathVariable("username") String username) {
		logger.info("deleteToken[{}]" , username);
		// 验证
		if (StringUtils.isEmpty(username)) {
			return Result.error("用户账号，不能为空!");
		}
		try {
			tokenManager.deleteToken(username);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("销毁TOKEN失败");
		}
		return Result.success();
	}

}
